import USER_AVATAR from '@/assets/image/user_avatar.png';
import { outLogin } from '@/services/ant-design-pro/login';
import { LogoutOutlined } from '@ant-design/icons';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, useIntl, useModel } from '@umijs/max';
import { Avatar, message } from 'antd';
import Cookies from 'js-cookie';
import type { MenuInfo } from 'rc-menu/lib/interface';
import React, { useCallback } from 'react';
import HeaderDropdown from '../HeaderDropdown';

const AvatarName = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  return <span className="anticon">{currentUser?.name}</span>;
};

const AvatarDropdown = () => {
  /**
   * 退出登录，并且将当前的 url 保存
   */
  const intl = useIntl();

  const loginOut = async () => {
    await outLogin();
    localStorage.removeItem('__u_t');
    localStorage.removeItem('user');
    localStorage.removeItem('__u_func');
    Cookies.remove('sessionid');
    const defaultLoginSuccessMessage = intl.formatMessage({
      id: 'pages.logout.success',
      defaultMessage: '已退出登录！',
    });
    message.success(defaultLoginSuccessMessage);
    history.replace('/user/login');
    // const { search, pathname } = window.location;
    // const urlParams = new URL(window.location.href).searchParams;
    // /** 此方法会跳转到 redirect 参数所在的位置 */
    // const redirect = urlParams.get('redirect');
    // // Note: There may be security issues, please note
    // if (window.location.pathname !== '/user/login' && !redirect) {
    //   history.replace({
    //     pathname: '/user/login',
    //     search: stringify({
    //       redirect: pathname + search,
    //     }),
    //   });
    // }
  };
  const actionClassName = useEmotionCss(({ token }) => {
    return {
      display: 'flex',
      height: '48px',
      marginLeft: 'auto',
      overflow: 'hidden',
      alignItems: 'center',
      padding: '0 8px',
      cursor: 'pointer',
      borderRadius: token.borderRadius,
      '&:hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });
  const { initialState, setInitialState } = useModel('@@initialState');

  const onMenuClick = useCallback(
    (event: MenuInfo) => {
      const { key } = event;
      if (key === 'logout') {
        // 删除存储在本地的 token和用户信息
        localStorage.removeItem('currentUser');
        localStorage.removeItem('token');
        loginOut();
        return;
      }
      history.push(`/account/${key}`);
    },
    [setInitialState],
  );

  const login = () => {
    history.push('/user/login');
  };

  // const loading = (
  //   <span className={actionClassName}>
  //     <Spin
  //       size="small"
  //       style={{
  //         marginLeft: 8,
  //         marginRight: 8,
  //       }}
  //     />
  //   </span>
  // );

  const loading = (
    <div className={actionClassName} onClick={login}>
      登錄
    </div>
  );

  if (!initialState) {
    return loading;
  }

  const { currentUser } = initialState;

  if (!currentUser || !currentUser.name) {
    return loading;
  }

  const menuItems = [
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <HeaderDropdown
      menu={{
        selectedKeys: [],
        onClick: onMenuClick,
        items: menuItems,
      }}
    >
      {/* <Avatar src={initialState?.currentUser?.avatar} style={{ marginRight: '7px' }} /> */}
      <Avatar src={<img src={USER_AVATAR} alt="avatar" />} style={{ marginRight: '7px' }} />
    </HeaderDropdown>
  );
};

const AvatarDef: React.FC = () => {
  const avatarCN = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'row',
      marginRight: '38px',
    };
  });
  return (
    <div className={avatarCN}>
      <AvatarDropdown></AvatarDropdown>
      <AvatarName></AvatarName>
    </div>
  );
};

export default AvatarDef;
